﻿#include "BaseDialog.h"

#include <QLabel>
#include <QVBoxLayout>
#include <QMouseEvent>
#include <QDebug>

BaseDialog::BaseDialog(QWidget *parent, QString title/*=""*/)
    : QDialog(parent)
{
    // 创建一个垂直布局，带标题栏和内容，如果标题为空就不创建标题栏
    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setSpacing(0);
    if (!title.isEmpty())
    {
        // 创建标题栏，需要在样式表里面设置样式
        m_titleBar = new QLabel(this);
        m_titleBar->setObjectName("baseDialogTitleBar");
        m_titleBar->setText(title);
        m_titleBar->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

        layout->addWidget(m_titleBar);
    }
}

void BaseDialog::setContentWidget(QWidget *widget)
{
    // 具体内容加入根布局
    QLayout* rootLayout = layout();
    rootLayout->addWidget(widget);
    if (rootLayout->count() > 1)
    {
        auto* layout = qobject_cast<QVBoxLayout*>(rootLayout);
        // 设置内容区域撑满可用区域
        if (layout) layout->setStretch(0, 1);
    }
}

void BaseDialog::mousePressEvent(QMouseEvent *e)
{
    // 在标题栏中按住左键可以拖动窗口
    if (e->button() == Qt::LeftButton &&
            m_titleBar->rect().contains(e->pos()))
    {
        m_lastPoint = e->globalPos() - frameGeometry().topLeft();
        e->accept();
    }
    // 右键关闭
    else if (e->button() == Qt::RightButton)
    {
        reject();
    }
}

void BaseDialog::mouseMoveEvent(QMouseEvent *e)
{
    if (!m_lastPoint.isNull() && e->buttons() & Qt::LeftButton)
    {
        move(e->globalPos() - m_lastPoint);
        e->accept();
    }
}

void BaseDialog::mouseReleaseEvent(QMouseEvent *)
{
    if (!m_lastPoint.isNull())
    {
        m_lastPoint = QPoint();
    }
}
